<template>
    <div id="add-edit-WaitReview">
        <el-dialog
            title="登记复查结果"
            v-model="isUseDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="60%" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="80px" :rules="rules">
                <el-row :gutter="35">
                    <el-divider content-position="left">基础数据</el-divider>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="复查时间" prop="d_ReviewTime">
                            <el-date-picker
                                v-model="ruleForm.d_ReviewTime"
                                type="date"
                                value-format="YYYY-MM-DD"
                                placeholder="请选择开始日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="复查结果">
                            <el-select 
                                class="m-2" 
                                placeholder="请选择复查结果" 
                                v-model="ruleForm.n_ReviewResult"
                            >
                                <el-option
                                    v-for="item in resultOption"
                                    :key="item.id"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="验收部门" prop="l_AcceptanceDeptId">
                            <el-cascader 
                                v-model="ruleForm.l_AcceptanceDeptId"
                                :options="orgOption" 
                                :props="orgProps" 
                                @change="orgChange"
                                clearable 
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="验收人员" prop="l_AcceptanceUserId">
                            <el-select 
                                v-model="ruleForm.l_AcceptanceUserId" 
                                filterable 
                                class="m-2" 
                                placeholder="选择复查人员" 
                                @change="useChange"
                                value-key="id"
                                popper-class="set-select"
                                :popper-append-to-body="false"
                            >
                                <el-option
                                    v-for="item in useOptions"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label="复查意见" prop="v_ReviewOpinion">
                            <el-input type="textarea" v-model="ruleForm.v_ReviewOpinion" placeholder="请输入复查意见" clearable />
                        </el-form-item>
                    </el-col>
                    <el-divider content-position="left">复查图片上传</el-divider>
                    <div style="padding: 0 20px;width: 100%;">
                        <FileView
                            ref="fileRef"
                            isAccept=".jpg,.jpeg,.png"
                            :fileInfo="fileInfo"
                            :componentKey="componentKey"
                        />
                    </div>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">取消</el-button>
                <el-button type="primary" :loading="repeatDis" :disabled="repeatDis" @click="submitForm(ruleFormRef)">提交</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRef , toRefs , toRaw , onMounted , watch } from 'vue';
import { 
    FormInstance, 
    FormRules, 
    ElButton, 
    ElCol, 
    ElDialog, 
    ElDivider, 
    ElForm, 
    ElFormItem, 
    ElOption, 
    ElRow, 
    ElSelect,
    ElMessage,
} from 'element-plus';
import { sysUserSelector , sysFileInfoMultipleUpload } from '/@/api/centerControl/pubilc';
import FileView from '../file-view.vue';
import { SMSHDRectifyReviewResult } from '/@/api/centerControl/sms';
/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    id: Number, // 记录id
    d_ReviewTime: String, // 复查时间
    n_ReviewResult: Number, // 隐患复查结果
    v_ReviewOpinion: String, // 复查意见
    l_AcceptanceDeptId: any, // 验收部门id
    l_AcceptanceUserId: any, // 验收人员id
}
export default defineComponent( {
    name: 'add-edit-WaitReview',
    components: {FileView},
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        },
        bascObj: {
            type: Object,
            default: {},
        }
    },
    setup(props,ctx){
        const ruleFormRef = ref();
        const orgOption = ref();
        const useOptions = ref();
        const fileRef = ref();
        const fileInfo = ref();

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            d_ReviewTime: [
				{ required: true, message: '请选择复查时间', trigger: 'change' },
			],
            v_ReviewOpinion: [
				{ required: true, message: '请输入复查意见', trigger: 'blur' },
			],
            l_AcceptanceDeptId: [
				{ required: true, message: '请选择验收部门', trigger: 'change' },
			],
            l_AcceptanceUserId: [
				{ required: true, message: '请选择验收人员', trigger: 'change' },
			],
        })

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            ctx.emit('cancelUseClick')
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            ctx.emit('cancelUseClick')
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => { 
                if(valid){
                    state.repeatDis = true;
                    let item = state.ruleForm;
                    fileFun(item);
                }else{
                    console.log('error submit!')
					return false
                }
            })
        }

        /*** 文件上传 */
        const fileFun = async(val: any) => {
            if(fileRef.value.fileList.length !== 0){
                let setArr:any = [];
                fileRef.value.fileList.map((i: any) => {
                    setArr.push(i.raw);
                });
                let res: any;
                let param: any = {};
                param.files = setArr;
                param.sourceId = JSON.parse(props.repairInfo).l_ReviewFileId;
                param.sourceType = 10;
                try{
                    res = await SMSHDRectifyReviewResult(val);
                    if(res.success){
                        try{
                            let rcs: any = await sysFileInfoMultipleUpload(param);
                            if(rcs.success){
                                state.repeatDis = false;
                                ctx.emit('controlUseClick');
                                ctx.emit('updateData');
                            }else{
                                state.repeatDis = false;
                                ctx.emit('controlUseClick');
                            }
                        }catch(error){state.repeatDis = false; }
                    }else{
                        state.repeatDis = false;  
                    }
                }catch(error){ state.repeatDis = false; }
            }else{
                ElMessage({
                    type: 'warning',
                    message: '请上传整改图片',
                    duration: 1000,
                    onClose: () => {
                        state.repeatDis = false;
                    }
                })
            }
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }

        // 获取用户数据
        const useFun = async(id: number) => {
            let param: any = {};
            param.orgId = id;
            let res:any = await sysUserSelector(param)
            if(res.success){
                useOptions.value = res.data;
            }
        }

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                if(Object.keys(props.bascObj).length !== 0){
                    let treeData = JSON.parse(props.bascObj.treeData);
                    if(treeData !== ''){
                        orgOption.value = treeData;
                    }
                }
                let item = JSON.parse(props.repairInfo);
                fileInfo.value = JSON.stringify({sourceId: item.l_ReviewFileId});
                state.ruleForm = {
                    id: JSON.parse(props.repairInfo).id, // 整改记录id
                    d_ReviewTime: '', // 复查时间
                    n_ReviewResult: 0, // 隐患复查结果
                    v_ReviewOpinion: '', // 复查意见
                    l_AcceptanceDeptId: '', // 验收部门id
                    l_AcceptanceUserId: '', // 验收人员id
                }
            }
        })

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

        /*** 复查部门改变事件 */
        const orgChange = (val: any) => {
            let len = val.length - 1;
            if(val && val.length !== 0){
                state.ruleForm.l_AcceptanceDeptId = val[len];
                state.ruleForm.l_AcceptanceUserId = ''; // 隐患排查人员id
                useFun(val[len]);
            }
        }

        /*** 复查人员改变事件 */
        const useChange = (val: any) => {
            
        }

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            ...toRefs(state),
            isUseDialog,
            resultOption: [
                {id: 0, label: '已整改', value: 0},
                {id: 1, label: '未整改', value: 1},
                {id: 2, label: '整改不符合要求', value: 2}
            ],
            rules,
            orgProps: { checkStrictly: true , label: 'title', value: 'id', children: 'children' },
            orgOption,
            orgChange,
            useOptions,
            useChange,
            componentKey: 1,
            fileInfo,
            fileRef,
        }
    },
} )
</script>
<style scoped lang="scss">
#file-view{
    width: 100%;
}
:deep(.el-cascader){
    width: 100%;
}
:deep(.el-select){
    width: 100%!important;
}
:deep(.el-input){
    width: 100%;
}
</style>